/**
 * @(#) DailyMediator.as
 *
 * @date		2009. 04. 03.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	상시출장  신청 - Mediator
 * 				상시출장을 조회하고 신청하는 Presentation Logic을 관리 
 */
package com.skt.common_hr.biztrip.view 
{
	import com.skt.common_hr.biztrip.BizTripFacade;
	import com.skt.common_hr.biztrip.model.BizTripBudgetProxy;
	import com.skt.common_hr.biztrip.model.DailyApprovalProxy;
	import com.skt.common_hr.biztrip.model.DailyBizTripProxy;
	import com.skt.common_hr.biztrip.model.DailyCostProxy;
	import com.skt.common_hr.biztrip.model.vo.BizTripListVO;
	import com.skt.common_hr.biztrip.model.vo.BizTripPlaceVO;
	import com.skt.common_hr.biztrip.model.vo.DailyCostVO;
	import com.skt.common_hr.biztrip.view.components.DailyBizTrip;
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.approval.RequestApprovalMediator;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.wcl.components.Hourglass;
	import com.wcl.utils.DateUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class DailyMediator extends CommonMediator
	{
		public static const NAME:String = "DailyMediator"; 

		private var key1:String;
		private var key2:String;
		private var TRSTATUS:String = "21";
		private var bModify:Boolean = true;
		
		private var bWaitingApproval:Boolean = false;
		private var _currentKey:String = "";
		private var currentDate:Date = new Date;
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function DailyMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		private function initView():void
 		{
 			initDataProvider();
			//loadBizTripList();
			//set event handlers...
			
			view.addEventListener(DailyBizTrip.ADD_RECORD, onAddRecord);
			view.addEventListener(DailyBizTrip.DEL_RECORD, onDelRecord);
			view.addEventListener(DailyBizTrip.SAVE, onSave);
			view.addEventListener(DailyBizTrip.APPROVAL, onApproval);
			view.addEventListener(DailyBizTrip.CANCEL, onInputCancel);
 		}
 		
 		override protected function clearView():void
 		{
 			modeModify();
 			key1 = "";
 			key2 = "";
 			TRSTATUS = "21";
 			view.dailyCost = 0;
 			view.strStatus = "(신규 신청중)";
 			initDataProvider();
 		}
 		
 		private function modeReadOnly():void
 		{
 			bModify = false;
 			view.currentState = "readonly";
 		}
 		
 		private function modeModify():void
 		{
 			bModify = true;
 			view.currentState = "";
 		}
		private function initDataProvider():void
		{
			var arr:ArrayCollection = new ArrayCollection();
			currentDate = DateUtil.todayNoTime();
			arr.addItem(blankRecord());
			view.dailyDP = arr;
			loadDailyCost(1);
		}
		
		private function loadDailyCost(days:int):void
		{
			var proxy:DailyCostProxy = facade.retrieveProxy(DailyCostProxy.NAME) as DailyCostProxy;
			proxy.load(Variables.myPernr, BizTripFacade.TYPE_DAILY_BIZTRIP, days, new Date(), new Date());
		}
		
		
		private function loadDailyBizTrip(vo:BizTripListVO):void
		{
			key1 = vo.GWAREKEY01;
			key2 = vo.GWAREKEY02;
			TRSTATUS = vo.TRSTATUS;
			var proxy:DailyBizTripProxy = facade.retrieveProxy(DailyBizTripProxy.NAME) as DailyBizTripProxy;
			proxy.load(key1, key2);
		}

//shgoo : 2009.06.01
		/**
		*  가용예산을 로드한다.
		* @param
		* @return void
		*/
		private function loadBudget(pernr:String):void
		{
			var budgetProxy:BizTripBudgetProxy = facade.retrieveProxy(BizTripBudgetProxy.NAME) as BizTripBudgetProxy;
			budgetProxy.load(pernr, BizTripFacade.TYPE_DAILY_BIZTRIP);
		}
//////////////////////

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					BizTripFacade.LOAD_DAILY_COST_COMPLETE,
					BizTripFacade.LOAD_DAILY_COST_FAILED,
					BizTripFacade.LOAD_DAILY_BIZTRIP_COMPLETE,
					BizTripFacade.LOAD_DAILY_BIZTRIP_FAILED,
					BizTripFacade.SAVE_DAILY_BIZTRIP_COMPLETE,
					BizTripFacade.SAVE_DAILY_BIZTRIP_FAILED,
					BizTripFacade.MODIFY_DAILY_VIEW,
//shgoo : 2009.06.01
					BizTripFacade.LOAD_BUDGET_COMPLETE,
					BizTripFacade.LOAD_BUDGET_FAILED,
					BizTripFacade.LOAD_BUDGET_DAILY_REQUEST,
////////////////////					
					BizTripFacade.READONLY_DAILY_VIEW,
					RequestApprovalMediator.APPROVAL_CANCEL,
					RequestApprovalMediator.APPROVAL_COMPLETE
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case BizTripFacade.READONLY_DAILY_VIEW:
					clearView();
					loadDailyBizTrip(note.getBody() as BizTripListVO);
					modeReadOnly();
					break;
				case BizTripFacade.MODIFY_DAILY_VIEW:
					clearView();
					if(note.getBody()!=null) {
						loadDailyBizTrip(note.getBody() as BizTripListVO);
					}
					modeModify();
					break;
				case BizTripFacade.LOAD_DAILY_COST_COMPLETE:
					setDailyCost((note.getBody() as DailyCostProxy).costList.getItemAt(0) as DailyCostVO);
					break;
				case BizTripFacade.LOAD_DAILY_BIZTRIP_COMPLETE:
					setDataToView(note.getBody() as DailyBizTripProxy);
					commonFacade.setStatusMessage("STATUS_LOAD_DAILY_BIZTRIP");
					break;
				case BizTripFacade.SAVE_DAILY_BIZTRIP_COMPLETE:
					if(bWaitingApproval) {
						bWaitingApproval = false;
						_currentKey = DailyBizTripProxy(note.getBody()).outKey;
						CommonAlert.showMsgYesNo(commonFacade.bundle, "ALERT_ASK_APPROVAL", null, "ALERT_TITLE_INFO", null,
							execApproval, null );						
					}
					else {
						changeListView();
					}
					break;
				case BizTripFacade.SAVE_DAILY_BIZTRIP_FAILED:
					Hourglass.remove();
					CommonAlert.showMessage(commonFacade.bundle, "("+note.getBody().retCode+")"+note.getBody().retText);
					//	_currentKey = DailyBizTripProxy(note.getBody()).outKey;
					//	CommonAlert.showMsgYesNo(commonFacade.bundle, "ALERT_ASK_APPROVAL", null, "ALERT_TITLE_INFO", null,
					//		execApproval, null );						
					break;
//shgoo : 2009.06.01 가용예산 표시
				case BizTripFacade.LOAD_BUDGET_DAILY_REQUEST:
					commonFacade.setStatusMessage("STATUS_START_DAILY_BIZTRIP");
					//loadBudget(Variables.myPernr);
					break;
				case BizTripFacade.LOAD_BUDGET_COMPLETE:
					//onLoadBudget(note.getBody() as BizTripBudgetProxy);
					break;
/////////////////////
				case RequestApprovalMediator.APPROVAL_COMPLETE:					// 결재 요청  성공
					changeListView();
					break;
				case RequestApprovalMediator.APPROVAL_CANCEL:					// 결재 요청 취소
					//cancelApproval(_currentKey);
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
		
		
		

//shgoo : 2009.06.01
  		private function onLoadBudget(proxy:BizTripBudgetProxy):void
 		{
 			view.budget = proxy.budget;
/* 			
 			if(adjustBase == null) {
 				adjustBase = new AdjustBaseVO();
 			}
 			adjustBase.KOSTL = proxy.KOSTL;
 			adjustBase.WERT1 = proxy.budget;
 			adjustBase.WAERS = proxy.wares;
 			adjustBase.KDATE = new Date();
 			adjustBase.KURSF01 = 0;
 			adjustBase.KURSF02 = 0;
*/ 			
 		}
//////////////////////
		
 		private function setDataToView(proxy:DailyBizTripProxy):void
 		{
 			//trace("setDatatoView: " + proxy.places.length);
 			view.dailyDP = proxy.places;
 			if(!bModify) {
 				if(String("11,21").indexOf(proxy.adjusts.getItemAt(0).TRSTATUS)>-1) {
 					view.btnModify.visible = true;
 				}
 				else {
 					view.btnModify.visible = false;
 				}
 			}
 			view.strStatus = proxy.adjusts.getItemAt(0).TRSTATX;
			//출장비			
 			view.dailyCost = proxy.adjusts.getItemAt(0).DAYPY;
 		}
 
 
 
 
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		private function onAddRecord(event:Event):void
		{
			view.dailyDP.addItem(blankRecord());
			loadDailyCost(view.dailyDP.length);
		}
		
		private function onDelRecord(event:Event):void
		{
			for (var i:int=0; i<view.dailyDP.length; i++)
			{
				if(view.dailyDP.getItemAt(i).del) {
					view.dailyDP.removeItemAt(i--);
				}
			} 			
			if(view.dailyDP.length==0) {
				view.dailyDP.addItem(blankRecord());
			}
			loadDailyCost(view.dailyDP.length);
		}
		
		private function onSave(event:Event):void
		{
			if(checkTables()) {
				var proxy:DailyBizTripProxy = facade.retrieveProxy(DailyBizTripProxy.NAME) as DailyBizTripProxy
				proxy.save(Variables.myPernr, false/*임시저장*/, TRSTATUS, key1, key2, bizTripPlaces(), adjustmentTable());
			}
			else {
			}
		}
		
		private function onApproval(event:Event):void
		{
			if(checkTables()) {
				if(Number(view.txtDailyCost.dataValue)!=0) {
					bWaitingApproval = true;
					var proxy:DailyBizTripProxy = facade.retrieveProxy(DailyBizTripProxy.NAME) as DailyBizTripProxy
					proxy.save(Variables.myPernr, true/*임시저장*/, TRSTATUS, key1, key2, bizTripPlaces(), adjustmentTable());
				}
				else {
					view.txtDailyCost.setFocus();
					CommonAlert.showMessage(commonFacade.bundle, "출장비를 입력하셔야 승인요청을 할 수 있습니다.", null, "TITLE_DEFAULT", view);
				}
			}
		}
		private function execApproval():void
		{
			if(checkTables()) {
	 			var approval:RequestApprovalMediator = facade.retrieveMediator(RequestApprovalMediator.NAME) as RequestApprovalMediator;
	 			if(approval==null) {
	 				approval = new RequestApprovalMediator(view, "04");
	 				facade.registerMediator(approval);
	 			}
	 			
	 			var appProxy:DailyApprovalProxy = facade.retrieveProxy(DailyApprovalProxy.NAME) as DailyApprovalProxy;
	 			appProxy.key =_currentKey;
	 			appProxy.amount = view.txtDailyCost.text;
	 			appProxy.dataProvider = view.dailyDP;
	 			
	 			approval.execRequest(view, appProxy); // 국내는. 무조건 포함. bTRPAYC : 정산포함여부
			}

		}
		
		
		private function onCancelApproval():void
		{
			//Hourglass.remove();
		}
		
		
				
		private function checkTables():Boolean
		{
			var dateList:Array = new Array();
			for each(var vo:BizTripPlaceVO in view.dailyDP) {
				if(vo.BREN==null || vo.BREN == "") {
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_PLACE", null, "TITLE_DEFAULT", view);
					return false;
				}
				dateList.push(vo.BEGDA);
			}
			if(dateList.length>=2) {
				dateList.sort(Array.NUMERIC);
				var tmpDate:Date = new Date(dateList[0]);
				for(var i:int=1; i<dateList.length; i++) {
					tmpDate.date++;
					if(dateList[i].fullYear != tmpDate.fullYear || 
							dateList[i].month != tmpDate.month || 
							dateList[i].date != tmpDate.date)
					{
						CommonAlert.showMessage(commonFacade.bundle, "시내출장은 연속된 일자로만 동시 신청이 가능합니다.", null, "TITLE_DEFAULT", view);
						return false;
					}
				}
			}
			/*
//shgoo : 2009.06.25			
//			if(Number(view.txtDailyCost.text)>view.dailyDP.length*5000) {
			var dataValue:String = view._budget.replace( new RegExp(",", "g"), "");
			if(Number(view.txtDailyCost.dataValue) > Number(dataValue) ) {
//////////////////////				
				CommonAlert.showMessage(commonFacade.bundle, "ALERT_OVER_COST", null, "TITLE_DEFAULT", view);
				return false;
			}
			*/
			return true;
		}
		private function bizTripPlaces():Array
		{
			var table:Array = new Array;
			for each(var vo:BizTripPlaceVO in view.dailyDP) {
				var tmp:Object = new Object;
				tmp.SEQNO = vo.SEQNO;
				tmp.BEGDA = DateUtil.toBasicString(vo.BEGDA);
				tmp.ENDDA = DateUtil.toBasicString(vo.ENDDA);
				tmp.LAND1 = vo.LAND1;
				tmp.LANDTX = vo.LANDTX;
				tmp.LAGBN = vo.SEQNO;
				tmp.BREN = vo.BREN;
				table.push(tmp);
			}
			return table;
		}
		
		private function adjustmentTable():Array
		{
			var table:Array = new Array();
			//var rec:AdjustmentVO = new AdjustmentVO();
			var rec:Object = new Object;
			rec["WERT1"] = 0;
			if(Number(view.txtDailyCost.dataValue)!=0) {
				rec["DAYPY"] = Number(view.txtDailyCost.dataValue)/100; //view.dailyCost/100;
			}
			else {
				rec["DAYPY"] = 0;
			}
			//trace(rec["DAYPY"]);
			table.push(rec);
			return table;
		}
		
		private function onInputCancel(event:Event):void
		{
			changeListView();
		}
		
		private function changeListView():void
		{
			clearView();
			bActivated = false;
			facade.sendNotification(BizTripFacade.CHANGE_VIEW_BIZTRIP_LIST, this);
		}
		
		private function blankRecord():BizTripPlaceVO
		{
			var rec:BizTripPlaceVO = new BizTripPlaceVO();
			rec.BEGDA = new Date(currentDate);
			rec.ENDDA = new Date(currentDate);
			currentDate.date += 1;
			return rec;
		}
 		
		private function setDailyCost(vo:DailyCostVO):void
		{
			//view.dailyCost = vo.AMT;
			view.maxDailyCost = vo.AMT;
		}
  		
 		




		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():DailyBizTrip
        {
            return viewComponent as DailyBizTrip;
        }
		
		
	}
}